import Vue from "vue";
import App from "./App.vue";
// 1引入vuex
import Vuex from "vuex";
// 2让Vue食用vuex
Vue.use(Vuex);
// 3创建仓库实例
const store = new Vuex.Store({
  // 在仓库里写配置项
  state: {
    goodList: [
      {
        name: "诸葛亮",
        price: 1000,
        num: 1,
        checked: false,
      },
      {
        name: "蔡文姬",
        price: 1500,
        num: 1,
        checked: false,
      },
      {
        name: "妲己",
        price: 2000,
        num: 1,
        checked: false,
      },
      {
        name: "鲁班",
        price: 2200,
        num: 1,
        checked: false,
      },
    ],
  },
  mutations: {
    // 数量减少
    reduceNumFn(state, ind) {
      // console.log(ind);
      // console.log(state.goodList[ind].num);
      // console.log(state);
      if (state.goodList[ind].num > 0) state.goodList[ind].num -= 1;
    },
    // 数量增加
    addNumFn(state, ind) {
      state.goodList[ind].num += 1;
    },
    // 删除商品
    delFun(state, ind) {
      //  console.log(ind);
      state.goodList.splice(ind, 1);
    },
    // 全选控制单选
    SelectAllFn(state, v) {
      // console.log(state);
      console.log(v);
      // state.goodList.forEach((item) => console.log(item.checked));
      state.goodList.forEach((item) => {
        item.checked = v;
        // console.log(item.checked);
      });
    },
  },
  actions: {},
  getters: {
    // 合计函数
    total(state) {
      // return state.goodList.length;
      return state.goodList.reduce((sum, item) => {
        // console.log(item.checked);
        if (item.checked) {
          sum += item.num * item.price;
        }
        return sum;
      }, 0);
    },
  },
});

Vue.config.productionTip = false;
// 4让vuex仓库实例和vue实例关联
new Vue({
  store,
  render: (h) => h(App),
}).$mount("#app");
